package com.android.memory;

import com.android.memory.R;
import com.android.memory.Card.Status;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class GameActivity extends Activity {
	private static int difficulty=2; 
	private int x,y,d,numberOfPairs;
	private int clickCounter = 0;
	Handler checkIfSameHandler = new Handler();
	private Card tempCard,tempCard2;
	private static MediaPlayer mp, mp2;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case R.id.text:     
	        	finish();
	            break;
	    }
	    return true;
	}
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        // Mediaplayers for flipsounds
        mp = MediaPlayer.create(this, R.raw.cardflip);
        mp2 = MediaPlayer.create(this, R.raw.cardflop);
        
        /* Checks Difficulty
         * x,y size of cards. Used in ImageAdapter.
         * numberOfPairs used to check when game is done.
         */
        if(difficulty == 3) { 
        	setContentView(R.layout.easygrid);
        	x = 110;
        	y = 110;
        	d = 1;
        	numberOfPairs = 8;
        }
        else if(difficulty == 2) {
        	setContentView(R.layout.mediumgrid);
        	x = 100;
        	y = 100;
        	d = 2;
        	numberOfPairs = 18;
        }
        else if	(difficulty == 1) {
        	setContentView(R.layout.hardgrid);
        	x = 90;
        	y = 90;
        	d = 3;
        	numberOfPairs = 24;
        }
        else 
        	finish();
        	
        // Create our gridview and ImageAdapter
        GridView gridview = (GridView) findViewById(R.id.gridview);
        gridview.setAdapter(new ImageAdapter(this, x, y, d));
        
        //Listener for card clicks
        gridview.setOnItemClickListener(new OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        		Card card = (Card) v;
        		// Starts cardflip sounds if turned on in options.
        		if((OptionsActivity.soundPlayer)==true)
        			mp.start();
        		
        		/* First card is pressed and turned over
        		 * clickCounter gets increased to 1
        		 */
        		if(card.getStatus().equals(Status.HIDDEN) && clickCounter == 0) {		
        			tempCard = card;
        	 		card.setStatus(Status.VISIBLE);
        	 		clickCounter = 1;
        	 	}
        		
        		/* Second card is pressed and turned over
        		 * postInvalidate is used to update the screen
        		 * Handler and runnable used to check if the cards are the same
        		 */
        	 	if(card.getStatus().equals(Status.HIDDEN) && clickCounter == 1) {
        	 		tempCard2 = card;
        	 		tempCard2.setStatus(Status.VISIBLE);
        	 		card.postInvalidate();
        	 		clickCounter = 2;
        	 		checkIfSameHandler.postDelayed(checkIfSameRunnable, 750);
        	 	}
        	} 
        });
    }
    
    /* Runnable to perform checks on the cards
     * also checks if the game is completed
     */
    private Runnable checkIfSameRunnable = new Runnable() {
    
    public void run() {
    	
    	if((OptionsActivity.soundPlayer)==true)
			mp2.start();
    	
	 	if(!tempCard2.equals(tempCard)) {
	 		tempCard2.setStatus(Status.HIDDEN);
	 		tempCard.setStatus(Status.HIDDEN);
	 	}
	 	else if(tempCard2.equals(tempCard)) {
	 		tempCard2.setStatus(Status.MISSING);
	 		tempCard.setStatus(Status.MISSING);
	 		//Removes pairs
	 		numberOfPairs = numberOfPairs - 1;
	 		if(numberOfPairs == 0)
	 			popupMenu();
	 	}
	 	clickCounter = 0;
      }
    };
    
    
    /* Pop up menu.
     * Shown when Game is finished
     */
    public void popupMenu(){
		AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
			alertbox.setMessage("Want to play again?");
			alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
             // Click listener 
             public void onClick(DialogInterface arg0, int arg1) {
                 Intent gameIntent = getIntent();
                 finish();
     			 startActivity(gameIntent);
             }
         });
         // Set a negative/no button and create a listener
         alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
             // Click listener
             public void onClick(DialogInterface arg0, int arg1) {
                finish();
             }
         });
         // display box
         AlertDialog alert = alertbox.create();
         alert.show();

    }
    
    
    public static void setDifficulty(int diff){
    	difficulty = diff;
    }
    
    public static int getDifficulty(){
    	return difficulty;
    }
    
    public void onStart() {
		super.onStart();
		//if music is on, then sets continueMusic to true
		if(OptionsActivity.musicPlayer)
			MusicManagerService.setContinueMusic(true);
	}
	
	public void onStop() {
		super.onStop();
		if(!MusicManagerService.getContinueMusic())
		{
	    	Intent backgroundmusic= new Intent(this, MusicManagerService.class);
			stopService(backgroundmusic);
		}
	}
	
	public void onPause() {
		super.onPause();
		MusicManagerService.setContinueMusic(false);
	}
	
	public void onResume() {
		super.onResume();
		if(OptionsActivity.musicPlayer) {
			MusicManagerService.setContinueMusic(true);
	    	Intent backgroundmusic= new Intent(this, MusicManagerService.class);
			startService(backgroundmusic);
		}
	}
	
	public void onDestroy() {
		super.onDestroy();
		checkIfSameHandler.removeCallbacks(checkIfSameRunnable);
	}
}


